package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"ports/cache"
	"ports/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")

	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Ports{
		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "发布失败",
		})
		return
	}
	var port models.Ports
	models.DB.Where("id = ?", data.ID).First(&models.Ports{})
	redis_data_key := "port_" + strconv.Itoa(int(data.ID))
	jsondata, _ := json.Marshal(port)
	cache.Rdb.Set(cache.Ctx, redis_data_key, jsondata, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	var ports []models.Ports

	redis_data_key := "port_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_data_key).Result()
	if cacheData == "" {
		models.DB.Find(&ports)
		jsonData, _ := json.Marshal(ports)
		cache.Rdb.Set(cache.Ctx, redis_data_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &ports)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": ports,
		"msg":  "查询成功",
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")
	models.DB.Where("id = ?" + id).Delete(&models.Ports{})

	redis_data_key := "port_" + id
	cache.Rdb.Del(cache.Ctx, redis_data_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
